import siteInfo from "../../siteinfo"

/**
 * 获取微擎请求的URI
 *
 * @param {string} uri     接口URI
 * @param {boolean} system 是否为系统接口
 * @returns {string}
 */
export function getUrl(uri,system = false)
{
    uri = makeQuery(uri)
    const base_url = siteInfo.siteroot
    const link_id = siteInfo.link_id
    let url
    if (!system){
        url = `${base_url}/module/${link_id}/${uri}`
    }else{
        url = `${base_url}/${uri}`
    }
    return url
}


/**
 * Object转URI请求字符串
 *
 * @param {Object} data
 * @returns {string}
 */
function queryParams(data = {}) {
    let result = []
    for (let key in data) {
        let value = data[key]
        if (['', undefined, null].indexOf(value) >= 0) {
            continue;
        }
        key = encodeURIComponent(key)
        if (value.constructor === Array) {
            value.forEach(value => {
                result.push(key + '[]=' + encodeURIComponent(value))
            })
        } else {
            result.push(key + '=' + encodeURIComponent(value))
        }
    }
    return result.join('&')
}

/**
 * 创建请求URI
 *
 * @param {string} uri
 * @returns {string}
 */
function makeQuery(uri) {
    let params = {};
    if (uri.indexOf("?") !== -1) {
        let uriInfo = uri.split('?');
        uri = uriInfo[0]
        let param = uriInfo[1].split("&");
        for (let i = 0; i < param.length; i++) {
            if (param[i].split("=")[0] && unescape(param[i].split("=")[1])) {
                params[param[i].split("=")[0]] =unescape(param[i].split("=")[1])
            }
        }
    }

    params = Object.assign(params,{
        account_id: siteInfo.account_id
    })

    if (params !== {}){
        uri = uri + "?" + queryParams(params)
    }
    return uri;
}
